﻿using MassTransit;
using SagaOrders.Application.Data;
using SagaOrders.Application.Data.Entities;
using SagaOrders.Application.Events;

namespace SagaOrders.Application.Services
{
    public class OrderService : IOrderService
    {
        private readonly IPublishEndpoint publishEnpoint;
        private readonly OrdersDbContext dbContext;

        public OrderService(IPublishEndpoint publishEnpoint,OrdersDbContext dbContext)
        {
            this.publishEnpoint = publishEnpoint;
            this.dbContext = dbContext;
        }
        async Task<bool> IOrderService.CreateOrder(Order order)
        {
           // 1. Save to database
           await dbContext.orders.AddAsync(order);

            // 2. Publish event

            var orderCreatedEvent = new OrderCreated()
            {
                CreatedAt=order.CreatedAt,
                OrderId=order.Id
            };

            await publishEnpoint.Publish(orderCreatedEvent);

            var result = await dbContext.SaveChangesAsync();
            return result > 0;

        }
    }
}
